﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RotovapPlatform.Domain.Business.Recipes.Entities
{
	/// <summary>
	/// 实验组实体
	/// </summary>
	public class ExperimentGroup
	{
		/// <summary>
		/// 实验组ID
		/// </summary>
		public Guid GroupId { get; set; }

		/// <summary>
		/// 实验组名称
		/// </summary>
		public string GroupName { get; set; }

		/// <summary>
		/// 实验组描述
		/// </summary>
		public string Description { get; set; }

		/// <summary>
		/// 创建时间
		/// </summary>
		public DateTime CreatedTime { get; set; }

		/// <summary>
		/// 创建人
		/// </summary>
		public string Creator { get; set; }

		/// <summary>
		/// 包含的配方列表（用于创建实验组）
		/// </summary>
		public ObservableCollection<RecipeDefinition> Recipes { get; set; } = new();

		/// <summary>
		/// 包含的实验列表（实际执行的实验）
		/// </summary>
		public ObservableCollection<Experiment> Experiments { get; set; } = new();

		/// <summary>
		/// 实验组状态
		/// </summary>
		public ExperimentGroupStatus Status { get; set; } = ExperimentGroupStatus.Pending;

		/// <summary>
		/// 预计总执行时间（分钟）
		/// </summary>
		public double EstimatedTotalTime => Recipes?.Sum(r =>
			r.RotovapParameters?.ProductParameters?.Sum(p => p.RotaryTime) ?? 0) ?? 0;

		/// <summary>
		/// 实际总执行时间（分钟）
		/// </summary>
		public double ActualTotalTime { get; set; }

		/// <summary>
		/// 实验组优先级
		/// </summary>
		public ExperimentPriority Priority { get; set; } = ExperimentPriority.Normal;

		/// <summary>
		/// 执行开始时间
		/// </summary>
		public DateTime? ExecutionStartTime { get; set; }

		/// <summary>
		/// 执行结束时间
		/// </summary>
		public DateTime? ExecutionEndTime { get; set; }

		/// <summary>
		/// 执行进度（0-100）
		/// </summary>
		public double ExecutionProgress { get; set; }

		/// <summary>
		/// 执行错误信息
		/// </summary>
		public string ErrorMessage { get; set; } = string.Empty;

		/// <summary>
		/// 执行人员
		/// </summary>
		public string Executor { get; set; }

		/// <summary>
		/// 从配方列表创建实验列表
		/// 注意：此方法仅在准备执行实验组时调用，不会在添加配方时自动调用
		/// </summary>
		public void CreateExperimentsFromRecipes()
		{
			if (Recipes == null || Recipes.Count == 0)
			{
				System.Diagnostics.Debug.WriteLine($"警告：实验组 {GroupId} 中没有配方，无法创建实验");
				return;
			}

			// 清空现有实验
			Experiments.Clear();
			System.Diagnostics.Debug.WriteLine($"开始为实验组 {GroupId} 创建实验，共 {Recipes.Count} 个配方");

			int order = 0;
			foreach (var recipe in Recipes)
			{
				try
				{
					// 确保配方参数完整
					if (recipe.RotovapParameters == null)
					{
						recipe.RotovapParameters = new Parameters.RotovapParameters();
						System.Diagnostics.Debug.WriteLine($"警告：配方 {recipe.RecipeId} 的参数为空，已创建默认参数");
					}

					// 创建实验
					var experiment = Experiment.FromRecipe(recipe, GroupId, order++);
					experiment.Priority = this.Priority; // 继承实验组的优先级
					Experiments.Add(experiment);

					System.Diagnostics.Debug.WriteLine($"已为配方 {recipe.RecipeId} 创建实验 {experiment.ExperimentId}");
				}
				catch (Exception ex)
				{
					System.Diagnostics.Debug.WriteLine($"为配方 {recipe.RecipeId} 创建实验时出错：{ex.Message}");
					// 继续处理下一个配方，不中断整个过程
				}
			}

			System.Diagnostics.Debug.WriteLine($"实验组 {GroupId} 创建实验完成，共创建 {Experiments.Count} 个实验");
		}

		/// <summary>
		/// 计算实验组的执行进度
		/// </summary>
		public void CalculateProgress()
		{
			if (Experiments == null || Experiments.Count == 0)
			{
				ExecutionProgress = 0;
				return;
			}

			ExecutionProgress = Experiments.Average(e => e.ExecutionProgress);
		}

		/// <summary>
		/// 更新实验组状态
		/// </summary>
		public void UpdateStatus()
		{
			if (Experiments == null || Experiments.Count == 0)
			{
				Status = ExperimentGroupStatus.Pending;
				return;
			}

			// 如果所有实验都完成
			if (Experiments.All(e => e.Status == ExperimentStatus.Completed))
			{
				Status = ExperimentGroupStatus.Completed;
				return;
			}

			// 如果所有实验都取消
			if (Experiments.All(e => e.Status == ExperimentStatus.Cancelled))
			{
				Status = ExperimentGroupStatus.Cancelled;
				return;
			}

			// 如果有任何一个实验失败
			if (Experiments.Any(e => e.Status == ExperimentStatus.Failed))
			{
				Status = ExperimentGroupStatus.Failed;
				return;
			}

			// 如果有任何一个实验正在运行
			if (Experiments.Any(e => e.Status == ExperimentStatus.Running))
			{
				Status = ExperimentGroupStatus.Running;
				return;
			}

			// 如果有任何一个实验暂停
			if (Experiments.Any(e => e.Status == ExperimentStatus.Paused))
			{
				Status = ExperimentGroupStatus.Paused;
				return;
			}

			// 默认为待执行
			Status = ExperimentGroupStatus.Pending;
		}
	}

	/// <summary>
	/// 实验组状态枚举
	/// </summary>
	public enum ExperimentGroupStatus
	{
		/// <summary>
		/// 待执行
		/// </summary>
		Pending,

		/// <summary>
		/// 执行中
		/// </summary>
		Running,

		/// <summary>
		/// 已完成
		/// </summary>
		Completed,

		/// <summary>
		/// 已取消
		/// </summary>
		Cancelled,

		/// <summary>
		/// 执行失败
		/// </summary>
		Failed,

		/// <summary>
		/// 已暂停
		/// </summary>
		Paused
	}


}
